package com.spgf.controller.fragments;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.archtecture.model.exceptions.NegocioException;
import com.spgf.controller.R;
import com.spgf.controller.utils.PadraoFragmentAb;
import com.spgf.model.dao.LancamentoDAO;
import com.spgf.model.entities.Lancamento;
import com.spgf.model.enums.Mes;
import com.spgf.model.rn.LancamentoRN;

public class LancamentoMnt extends PadraoFragmentAb {

	private ListView	listview;

	private Spinner		spnMeses;

	private TextView	txtTotal;

	@Override
	protected ViewGroup configurarViewRoot(LayoutInflater inflater) {
		return (ViewGroup) inflater.inflate(R.layout.fragment_lancamento_busca, null);
	}

	@SuppressWarnings("unchecked")
	protected boolean executarLongClick(AdapterView<?> pParent, View pView, int pPosition, long pID) throws NegocioException {

		if (pParent.getId() == R.id.lanc_busca_lista_resultado) {

			final Map<String, String> mapa = (Map<String, String>) listview.getItemAtPosition(pPosition);
			final String valor = mapa.get("SubItem").toString();
			final Integer codigo = Integer.valueOf(valor.substring(valor.indexOf("Ref.: ") + 6, valor.indexOf("Ref.: ") + 9));

			final LancamentoDAO dao = new LancamentoDAO(pView.getContext());
			dao.executeDelete(new Lancamento(codigo));

			atualizarLista(pParent);

			// DialogFragment dialog = AlertDialogFragment . newInstance ();
			// dialog . show ( getFragmentManager () , " progress ");

			// DialogFragment dialog = CustomDialogFragment . newInstance ();
			// dialog . show ( getFragmentManager () , " custom ");

			return true;

		}

		return false;

	};

	@SuppressLint("SimpleDateFormat")
	private void atualizarLista(final ViewGroup root) throws NegocioException {

		final LancamentoDAO dao = new LancamentoDAO(root.getContext());
		final Lancamento lancamento = new Lancamento();

		final Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MONTH, Mes.values()[spnMeses.getSelectedItemPosition()].ordinal());
		lancamento.setData(cal.getTime());

		final List<Lancamento> ls = new LancamentoRN(root.getContext()).executarFindAll(lancamento);

		Double valorTotal = 0.0;

		final ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (final Lancamento l : ls) {

			valorTotal += l.getValor();

			final DecimalFormat df = new DecimalFormat();

			df.setMinimumFractionDigits(2);
			df.setMaximumFractionDigits(2);

			final String valor = df.format(l.getValor());

			df.setMaximumFractionDigits(0);
			df.setMinimumIntegerDigits(3);

			final String referencia = df.format(l.getCodigo());

			final HashMap<String, String> item = new HashMap<String, String>();
			item.put("Item", new SimpleDateFormat("dd/MM/yyyy").format(l.getData()) + "                     R$ " + valor);
			item.put("SubItem", "Ref.: " + referencia + "                           " + l.getCategoria().getNome());

			list.add(item);
		}

		final String[] from = new String[] {"Item", "SubItem"};
		final int[] to = new int[] {android.R.id.text1, android.R.id.text2};
		listview.setAdapter(new SimpleAdapter(root.getContext(), list, android.R.layout.two_line_list_item, from, to));

		final DecimalFormat df = new DecimalFormat();
		df.setMinimumFractionDigits(2);
		df.setMaximumFractionDigits(2);

		txtTotal.setText("Total:                              R$ " + df.format(valorTotal));
	}

	private String[] popularComboMes() {

		final String[] array_spinner = new String[12];
		int count = 0;
		for (final Mes mes : Mes.values()) {
			array_spinner[count] = mes.getNome();
			count++;
		}

		return array_spinner;
	}

	@SuppressWarnings({"unchecked", "rawtypes"})
	@Override
	public void configurarTela(ViewGroup root) {

		listview = (ListView) root.findViewById(R.id.lanc_busca_lista_resultado);
		listview.setOnItemLongClickListener(acaolongClick);

		txtTotal = (TextView) root.findViewById(R.id.lanc_busca_txtTotal);
		txtTotal.setText("Total:                                R$ 000,00");

		spnMeses = (Spinner) root.findViewById(R.id.lanc_busca_spnMes);
		spnMeses.setAdapter(new ArrayAdapter(root.getContext(), android.R.layout.simple_spinner_dropdown_item, popularComboMes()));
		spnMeses.setSelection(Calendar.getInstance().get(Calendar.MONTH));
		spnMeses.setOnItemSelectedListener(acaoSelecionar);

		// atualizarLista(root);
	}

	@Override
	protected void executarSelecao(AdapterView<?> pParent, View pView, int pPosition, long pID) throws NegocioException {

		super.executarSelecao(pParent, pView, pPosition, pID);

		if (pParent.getId() == R.id.lanc_busca_spnMes) {
			atualizarLista(pParent);
		}
	}

}
